<?php

// +----------------------------------------------------------------------
// | ShintianCMS
// +----------------------------------------------------------------------
// | Copyright (c) 2011 Shintian All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: ljt <ljt1002@gmail.com>                                  
// +----------------------------------------------------------------------
class PublicAction extends Action {

    // 检查用户是否登录
    protected function checkUser() {
        if (!isset($_SESSION[C('USER_AUTH_KEY')])) {
            $this->assign('jumpUrl', PHP_FILE . C('USER_AUTH_GATEWAY'));
            $this->error(L("_NOT_LOGIN_"));
        }
    }

    // 菜单页面
    public function menu() {
        import('@.ORG.RBAC');
        $this->checkUser();
        if (isset($_SESSION[C('USER_AUTH_KEY')])) {
            //显示菜单项
             $menu = array();

             //读取应用分组
             $gmodel = M("Group");
             $gwhere ['status'] = 1;
             $gwhere ['show'] = 1;
             $appgrouplist = $gmodel->where($gwhere)->field('id,name,title')->order('sort asc')->select();
             $this->assign('appgroup', $appgrouplist);

            //读取数据库模块列表生成菜单项
            $node = M("Node");
            $id = $node->getField("id");
            $where ['level'] = 2;
            $where ['status'] = 1;
            $where ['pid'] = $id;
            $list = $node->where($where)->field('id,name,group_id,title')->order('sort asc')->select();
            if (C('USER_AUTH_TYPE') == 2) {
                //加强验证和即时验证模式 更加安全 后台权限修改可以即时生效
                //通过数据库进行访问检查
                $accessList = RBAC::getAccessList($_SESSION[C('USER_AUTH_KEY')]);
            } else {
                // 如果是管理员或者当前操作已经认证过，无需再次认证
                if ($_SESSION[$accessGuid]) {
                    return true;
                }
                //登录验证模式，比较登录后保存的权限访问列表
                $accessList = $_SESSION['_ACCESS_LIST'];
            }
            //dump($accessList);
            foreach ($list as $key => $module) {
                if (isset($accessList [strtoupper(APP_NAME)] [strtoupper($module ['name'])]) || $_SESSION ['st_administrator']) {
                    //设置模块访问权限
                    $module ['access'] = 1;
                    $menu [$key] = $module;
                }
            }
            if (!empty($_GET ['tag'])) {
                $this->assign('menuTag', $_GET ['tag']);
            }
            //dump($menu);
            //dump($grouplist);
            $this->assign('menu', $menu);
        }
        C('SHOW_RUN_TIME', false);   // 运行时间显示
        C('SHOW_PAGE_TRACE', false);
        $this->display();
    }

    // 后台首页 查看系统信息
    public function main() {
        $info = array(
            '操作系统' => PHP_OS,
            '运行环境' => $_SERVER["SERVER_SOFTWARE"],
            'PHP运行方式' => php_sapi_name(),
            'ThinkPHP版本' => THINK_VERSION . ' [ <a href="http://thinkphp.cn" target="_blank">查看最新版本</a> ]',
            '上传附件限制' => ini_get('upload_max_filesize'),
            '执行时间限制' => ini_get('max_execution_time') . '秒',
            '服务器时间' => date("Y年n月j日 H:i:s"),
            '北京时间' => gmdate("Y年n月j日 H:i:s", time() + 8 * 3600),
            '服务器域名/IP' => $_SERVER['SERVER_NAME'] . ' [ ' . gethostbyname($_SERVER['SERVER_NAME']) . ' ]',
            '剩余空间' => round((@disk_free_space(".") / (1024 * 1024)), 2) . 'M',
            'register_globals' => get_cfg_var("register_globals") == "1" ? "ON" : "OFF",
            'magic_quotes_gpc' => (1 === get_magic_quotes_gpc()) ? 'YES' : 'NO',
            'magic_quotes_runtime' => (1 === get_magic_quotes_runtime()) ? 'YES' : 'NO',
        );
        $this->assign('info', $info);
        $this->display();
    }

    // 用户登录页面
    public function login() {
        if (!isset($_SESSION[C('USER_AUTH_KEY')])) {
            $this->display();
        } else {
            $this->redirect('Index/index');
        }
    }

    public function index() {
        //如果通过认证跳转到首页
        $this->redirect('Index/index');
    }

    // 用户登出
    public function logout() {
        if (isset($_SESSION[C('USER_AUTH_KEY')])) {
            unset($_SESSION[C('USER_AUTH_KEY')]);
            unset($_SESSION['menu' . $_SESSION[C('USER_AUTH_KEY')]]);
            unset($_SESSION);
            session_destroy();
            $this->assign("jumpUrl", __URL__ . '/login/');
            $this->success(L("_LOGOUT_SUCCESS_"));
        } else {
            $this->error(L("_LOGOUT_ALREADY_"));
        }
    }

    // 登录检测
    public function checkLogin() {
        if (empty($_POST['account'])) {
            $this->error(L("_ACCOUNT_ERROR_"));
        } elseif (empty($_POST['password'])) {
            $this->error(L("_PASSWORD_REQUIRE_"));
        } elseif (empty($_POST['verify'])) {
            $this->error(L("_VERIFY_REQUIRE_"));
        }
        //生成认证条件
        $map = array();
        // 支持使用绑定帐号登录
        $map['account'] = $_POST['account'];
        $map["status"] = array('gt', 0);
        if ($_SESSION['verify'] != md5($_POST['verify'])) {
            $this->error(L("_VERIFY_ERROR_"));
        }
        import('@.ORG.RBAC');
        $authInfo = RBAC::authenticate($map);
        //使用用户名、密码和状态的方式进行认证
        if (false === $authInfo) {
            $this->error(L("_ACCOUNT_FORBID_"));
        } else {
            if ($authInfo['password'] != md5($_POST['password'])) {
                $this->error(L("_PASSWORD_ERROR_"));
            }
            $_SESSION[C('USER_AUTH_KEY')] = $authInfo['id'];
            $_SESSION['email'] = $authInfo['email'];
            $_SESSION['loginUserName'] = $authInfo['nickname'];
            $_SESSION['lastLoginTime'] = $authInfo['last_login_time'];
            $_SESSION['login_count'] = $authInfo['login_count'];
            if ($authInfo['account'] == 'admin') {
                $_SESSION['st_administrator'] = true;
            }
            //保存登录信息
            $User = M('User');
            $ip = get_client_ip();
            $time = time();
            $data = array();
            $data['id'] = $authInfo['id'];
            $data['last_login_time'] = $time;
            $data['login_count'] = array('exp', 'login_count+1');
            $data['last_login_ip'] = $ip;
            $User->save($data);

            // 缓存访问权限
            RBAC::saveAccessList();
            $this->success(L("_LOGIN_SUCCESS_"));
        }
    }

    // 更换密码
    public function changePwd() {
        $this->checkUser();
        //对表单提交处理进行处理或者增加非表单数据
        if (md5($_POST['verify']) != $_SESSION['verify']) {
            $this->error(L("_VERIFY_ERROR_"));
        }
        $map = array();
        $map['password'] = pwdHash($_POST['oldpassword']);
        if (isset($_POST['account'])) {
            $map['account'] = $_POST['account'];
        } elseif (isset($_SESSION[C('USER_AUTH_KEY')])) {
            $map['id'] = $_SESSION[C('USER_AUTH_KEY')];
        }
        //检查用户
        $User = M("User");
        if (!$User->where($map)->field('id')->find()) {
            $this->error(L("_PASSWORD_OLD_ERROR_"));
        } else {
            $User->password = pwdHash($_POST['password']);
            $User->save();
            $this->success(L("_PASSWORD_CHANGE_SUCCESS_"));
        }
    }

    public function profile() {
        $this->checkUser();
        $User = M("User");
        $vo = $User->getById($_SESSION[C('USER_AUTH_KEY')]);
        $this->assign('vo', $vo);
        $this->display();
    }

    public function verify() {
        $type = isset($_GET['type']) ? $_GET['type'] : 'gif';
        import("@.ORG.Image");
        Image::buildImageVerify(4, 1, $type);
    }

// 修改资料
    public function change() {
        $this->checkUser();
        $User = D("User");
        if (!$User->create()) {
            $this->error($User->getError());
        }
        $result = $User->save();
        if (false !== $result) {
            $this->success(L("_PROFILE_CHANGE_SUCCESS_"));
        } else {
            $this->error(L("_PROFILE_CHANGE_ERROR_"));
        }
    }

}

?>